package com.serviceprovider.business.module.admin.user.services.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.address.model.Address;
import com.serviceprovider.business.module.admin.address.services.IAddressService;
import com.serviceprovider.business.module.admin.role.model.Role;
import com.serviceprovider.business.module.admin.role.services.dao.interfaces.IRoleService;
import com.serviceprovider.business.module.admin.user.dao.interfaces.IUserDao;
import com.serviceprovider.business.module.admin.user.services.dao.interfaces.IUserService;
import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.user.model.impl.User;
import com.serviceprovider.business.module.user.model.impl.UserSearchCriteria;
import com.serviceprovider.business.utility.SecurityContextUser;
import com.serviceprovider.business.utility.maintenance.settings.RoleUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//~--- JDK imports ------------------------------------------------------------

import java.util.ArrayList;
import java.util.List;

/**
 * @Leonardo A. Auer
 *
 * @since 04/11/2011
 */
@Service("userService")
public class UserService implements IUserService {
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IRoleService    roleService;
    @Autowired
    private IUserDao        userDao;

    @Override
    public User getById(int id) {
        return userDao.findUserById(id);
    }

    public Page findAllLevel1Users() {
        Page       users            = findAll();
        List<User> filteredUserList = new ArrayList<User>();

        for (User user : (List<User>) users.getPageItems()) {

            // remove deleted users;
            if (user.isDeleted()) {
                continue;
            }

            // remove disabled users
            if (!user.isEnabled()) {
                continue;
            }

            // Remove all not service providers
            String role = (user.getRole() == null)
                          ? null
                          : roleService.getRoleById(user.getRole().getId()).getName();

            if (!RoleUtils.ROLE_SERVICE_PROVIDER.equals(role)) {
                continue;
            }

            // Remove myself
            if (user.getId().equals(getUserConnected().getId())) {
                continue;
            }

            // I am eligible to be level1User
            filteredUserList.add(user);
        }

        users.setPageItems(filteredUserList);

        return users;
    }

    @Override
    public Page<User> findAll() {
        return userDao.findAllUsers(1, 100, "id", "asc");
    }

    @Override
    public Page<User> findByRole(Role role) {
        return userDao.findUserByRole(role, 1, 100, "id", "asc");
    }

    @Override
    public User getByEmail(String email) {
        return userDao.findUserByUsername(email);    // email=username
    }

    @Override
    public void remove(int id) {
        userDao.deleteUser(id);
    }

    @Override
    public void unRemove(int id) {
        userDao.undeteleUser(id);
    }

    @Override
    public void save(User user) {
        userDao.insertUser(user);
    }

    @Override
    public void update(User user) {
        Address contactAddress  = user.getContactAddress();
        Address businessAddress = user.getBusinessAddress();
        Address shippingAddress = user.getShippingAddress();

        // Update address when it already exists
        if ((contactAddress != null) && (contactAddress.getId() != null)) {
            addressService.updateAddress(contactAddress);
        }

        if ((businessAddress != null) && (businessAddress.getId() != null)) {
            addressService.updateAddress(businessAddress);
        }

        if ((shippingAddress != null) && (shippingAddress.getId() != null)) {
            addressService.updateAddress(shippingAddress);
        }

        // Create address when it doesn't exist
        if ((contactAddress != null) && (contactAddress.getId() == null)) {
            addressService.insertAddress(contactAddress);
        }

        if ((businessAddress != null) && (businessAddress.getId() == null)) {
            addressService.insertAddress(businessAddress);
        }

        if ((shippingAddress != null) && (shippingAddress.getId() == null)) {
            addressService.insertAddress(shippingAddress);
        }

        userDao.updateUser(user);
    }

    @Override
    public void updateUserActiveFlag(int userId, boolean status) {
        userDao.updateActiveStatus(userId, status);
    }

    @Override
    public Page<User> findByIds(List<Integer> userIds, int pageNo, int recordSize, String sortColumn,
                                String sortOrder) {
        return userDao.findUsersById(userIds, pageNo, recordSize, sortColumn, sortOrder);
    }

    @Override
    public void updateUserActiveFlag(List<Integer> usersId, boolean status) {
        userDao.updateActiveStatus(usersId, status);
    }

    @Override
    public void updateUserInGuiFlag(List<Integer> usersId, boolean status) {
        userDao.updateInGuiFlag(usersId, status);
    }

    @Override
    public void remove(List<Integer> usersId) {
        userDao.deleteUser(usersId);
    }

    @Override
    public void unRemove(List<Integer> usersId) {
        userDao.undeteleUser(usersId);
    }

    @Override
    public Page<User> findUsersByLevel1User(int level1UserId, int pageNo, int recordSize, String sortColumn,
            String sortOrder) {
        return userDao.findUsersByLevel1User(level1UserId, pageNo, recordSize, sortColumn, sortOrder);
    }

    @Override
    public Page<User> findUsersByRoleAndLevel1User(int role, int level1UserId, int pageNo, int recordSize,
            String sortColumn, String sortOrder) {
        return userDao.findUsersByRoleAndLevel1User(role, level1UserId, pageNo, recordSize, sortColumn, sortOrder);
    }

    @Override
    public Page<User> findAll(int pageNumber, int recordSize, String sortColumn, String sortOrder) {
        return userDao.findAllUsers(pageNumber, recordSize, sortColumn, sortOrder);
    }

    @Override
    public Page<User> findUserByCriteria(UserSearchCriteria criteria, int pageNo, int recordSize, String sortColumn,
            String sortOrder) {
        return userDao.findUserByCriteria(criteria, pageNo, recordSize, sortColumn, sortOrder);
    }

    @Override
    public void retrieveLevel1User(List<User> userList) {
        userDao.retrieveLevel1User(userList);
    }

    @Override
    public void retrieveLevel1User(User user) {
        userDao.retrieveLevel1User(user);
    }

    @Override
    public User getUserConnected() {
        return this.getByEmail(SecurityContextUser.getUserName());
    }

    @Override
    public List<Long> getAllNonMatchingIds(Integer roleId) {
        return userDao.getAllNonMatchingIds(roleId);
    }

    @Override
    public void updateAllUsersActiveFlag(Integer roleId, Boolean isActive) {
        userDao.updateAllUsersActiveFlag(roleId, isActive);
    }

    @Override
    public User getBySSN(int ssn) {
        return userDao.findUserBySSN(ssn);
    }
}



